import store from '../store';
import * as types from '../store/action-types';

const loginPermission = async function(to, from, next) {
    let r = await store.dispatch(`user/${types.USER_VALIDATE}`);
    let needLogin = to.matched.some(item => item.meta.needLogin);
    if (!store.state.user.hasPermission) {
        if (needLogin) {
            if (r) {
                next();
            } else {
                next('/login');
            }
        } else {
            next();
        }
    } else {
        if (to.path === '/login') {
            next('/');
        } else {
            next();
        }
    }
}

export const menuPermission = async function(to, from, next) {
    if (store.state.user.hasPermission) {
        if (!store.state.user.menuPermission) {
            store.dispatch(`user/${types.ADD_ROUTE}`);
            next({...to, replace: true });
        } else {
            next();
        }
    } else {
        next();
    }
}

export const createWebSockect = async function(to, from, next) {
    if (store.state.user.hasPermission && !store.state.ws) {
        store.dispatch(`${types.CREATE_WEBSOCKET}`);
        next();
    } else {
        next();
    }
}

export default {
    loginPermission,
    menuPermission,
    createWebSockect
}